import { Button, Card, Select, Input, Table } from "antd";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { productListApi } from "../../api";
const { Option } = Select;
function Product() {
  const [productList, setProductList] = useState([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const navigate = useNavigate();
  useEffect(() => {
    getProductList();
  }, []);
  const addProduct = () => {
    navigate("/admin/products/product/add_update");
  };
  const pageChange = (newPage) => {
    setCurrent(newPage);
    getProductList(newPage);
  };
  async function getProductList(page = 1) {
    const res = await productListApi(page, 5);
    const { status, data } = res.data;
    if (status !== 0) return;
    console.log({ res });
    setProductList(data.list);
    setTotal(data.total);
  }
  const handleChange = () => {};

  const columns = [
    {
      title: "商品名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "描述",
      dataIndex: "desc",
      key: "desc",
    },
    {
      title: "价格",
      dataIndex: "price",
      key: "price",
      render: (price) => "$" + price,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => {
        return (
          <div>
            <Button>下架</Button>
            <span>{status}</span>
          </div>
        );
      },
    },
    {
      title: "操作",
      dataIndex: "opera",
      key: "opera",
      render: () => {
        return (
          <div>
            <Button type="link">详情</Button>
            <Button type="link">修改</Button>
          </div>
        );
      },
    },
  ];
  return (
    <div>
      <Card
        size="small"
        title={
          <div>
            <Select defaultValue="name" onChange={handleChange}>
              <Option value="name">按名称搜索</Option>
              <Option value="desc">按描述搜索</Option>
            </Select>
            <Input
              placeholder="请输入关键字"
              style={{ width: "20%" }}
              allowClear
            />
            <Button type="primary">搜索</Button>
          </div>
        }
        extra={
          <Button type="primary" onClick={addProduct}>
            添加商品
          </Button>
        }
      >
        <Table
          dataSource={productList}
          bordered
          columns={columns}
          rowKey="_id"
          pagination={{
            pageSize: 5,
            total,
            current,
            onChange: pageChange,
          }}
        />
      </Card>
    </div>
  );
}

export default Product;
